package com.zjitc.util;

/**
 * Created by Aspire on 2018/4/1.
 */

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheUtil {
    private static int DEFAULT_TIME = 30 * 60 * 1000;
    private static Map<Integer, Token> map = new ConcurrentHashMap<Integer, Token>();
    private static Thread thread;

    static {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (map.size() != 0) {
                        Token token = map.get(0);
                        for (int i = 1; i < map.size(); i++) {
                            if (token.date.getTime() > map.get(i).date.getTime()) {
                                token = map.get(i);
                            }
                        }
                        long minTime = System.currentTimeMillis() - token.date.getTime();
                        try {
                            Thread.sleep(DEFAULT_TIME > minTime ? DEFAULT_TIME - minTime : 0);
                            token.value = "";
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    public static String getValue(String key){
        if (StringUtils.isNotEmpty(key)){
            for (int i = 0; i < map.size(); i++) {
                if (key.equals(map.get(i).key)) {
                    return map.get(i).value;
                }
            }
        }
        return "";
    }

    public static void setValue(String key, String value){
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
            for (int i = 0; i < map.size(); i++) {
                Token t = map.get(i);
                if ("".equals(t.value)) {
                    t.key = key;
                    t.value = value;
                    t.date = new Date();
                    return;
                }
            }

            if (map.size() == 0) {
                thread.start();
            }
            map.put(map.size(), new Token(key, value, new Date()));
        }
    }
}

class Token{
    protected String key;
    protected String value;
    protected Date date;

    public Token(String key, String value, Date date) {
        this.key = key;
        this.value = value;
        this.date = date;
    }
}
